<?php

namespace app\common\model\banxi\word;

use app\common\enums\ResourcesTypeEnum;
use app\common\enums\WordStatusEnum;
use app\common\model\banxi\course\Lexicon;
use app\common\model\common\BaseModel;
use app\common\service\queue\QueueService;
use app\common\service\word\WordUtilsService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 教练
 */
class WordDictionary extends BaseModel
{

    use SoftDelete;

    protected $name = 'banxi_word_dictionary';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'statusCn',
        'phoneticSplitList',
        'metaVowelList',
        'metaConsonantList',
        'exampleSentenceList'
    ];
    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'isSynthesis' => 'boolean',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];
    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new WordStatusEnum)->getDescription($value) ?? '';
    }

    public function getPhoneticSplitListAttr($value, $data)
    {
        $value = $value ?: ($data['phoneticSplit'] ?? '');
        $value = $value ? json_decode($value, true) : [];
        $result = [];
        foreach ($value as $item) {
            $result[] = [
                'phonetic' => WordUtilsService::getFilterPhonetic($item),
                'audio' => WordUtilsService::getPhoneticVocalUrl($item, ResourcesTypeEnum::E3)
            ];
        }
        return $result;

    }

    public function getMetaVowelListAttr($value, $data)
    {
        $value = $value ?: ($data['metaVowel'] ?? '');
        $value = $value ? json_decode($value, true) : [];
        foreach ($value as &$item) {
            $item['pronounce'] = WordUtilsService::getFilterPhonetic($item['pronounce']);
            $item['audio'] = WordUtilsService::getPhoneticVocalUrl($item['pronounce'], ResourcesTypeEnum::E3);
        }
        return $value;
    }

    public function getMetaConsonantListAttr($value, $data)
    {
        $value = $value ?: ($data['metaConsonant'] ?? '');
        $value = $value ? json_decode($value, true) : [];
        foreach ($value as &$item) {
            $item['pronounce'] = WordUtilsService::getFilterPhonetic($item['pronounce']);
            $item['audio'] = WordUtilsService::getPhoneticVocalUrl($item['pronounce'], ResourcesTypeEnum::E3);
        }
        return $value;
    }

    public function getExampleSentenceListAttr($value, $data)
    {
        $value = $value ?: ($data['exampleSentence'] ?? '');
        $value = $value ? json_decode($value, true) : [];
        foreach ($value as &$item) {
            $item['audio'] = WordUtilsService::getVocalUrl($item['en'], ResourcesTypeEnum::E4);
        }
        return $value;
    }
    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function getByWord($word)
    {
        return $this->where(['word' => $word])->find();
    }

    public function getMetaConsonantList($metaConsonantList)
    {
        if (!empty($metaConsonantList)) {
            foreach ($metaConsonantList as &$item) {
                $item['pronounce'] = WordUtilsService::getFilterPhonetic($item['pronounce']);
            }
        }
        return $metaConsonantList;
    }

    public function getMetaVowelList($metaVowelList)
    {
        if (!empty($metaConsonantList)) {
            foreach ($metaConsonantList as &$item) {
                $item['pronounce'] = WordUtilsService::getFilterPhonetic($item['pronounce']);
            }
        }
        return $metaVowelList;
    }

    public function refreshDictInfo(array $dictionary, bool $isUpdate)
    {
        $word = $dictionary['word'];
        $phonetic = WordUtilsService::getFillPhonetic($dictionary['phonetic']);
        $dictionary['phonetic'] = $phonetic;
        $translation = $dictionary['translation'];
        $wordDictionary = $this->where(['word' => $word])->find();
        if ($wordDictionary) {
            if ($isUpdate) {
                if ($wordDictionary['status'] == WordStatusEnum::E1) {
                    throw new ValidateException('词典正在执行中，不可进行修改');
                }
                if ($wordDictionary['status'] == WordStatusEnum::E3) {
                    $dictionary['status'] = WordStatusEnum::E2;
                }
                $this->update($dictionary, ['word' => $word]);
                $lexiconModel = new Lexicon();
                $lexiconModel->updateTranslationByWord($word, $translation, $phonetic);
            }
        } else {
            $dictionary['isSynthesis'] = 0;
            $dictionary['status'] = WordStatusEnum::E1;
            $this->save($dictionary);
        }
        return true;
    }

    public function listByWord($words)
    {
        return $this->whereIn('word', $words)->select();
    }

    public function getListPage(array $where, string $page = "1", int $limit = 10)
    {
        return $this->where($where)
            ->hidden(['phoneticSplit', 'metaVowel', 'metaConsonant', 'exampleSentence'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ]);
    }

    public function getInfo(array $where)
    {
        return $this->where($where)->find();
    }

    public function getWordErrorCount()
    {
        return $this->where(['status' => WordStatusEnum::E3])->count();
    }


    public function resetWordErr($where)
    {
        $this->update(['status' => WordStatusEnum::E1], $where);
        $queueService = new QueueService();
        $queueService->addWordSplitJob();
        return true;
    }

    public function del($id)
    {
        try {
            $info = $this->where(['id' => $id])->find();
            if (empty($info)) {
                throw new ValidateException('单词不存在');
            }
            $word = $info['word'];
            $lexiconModel = new Lexicon();
            $courseIds = $lexiconModel->where(['word' => $word])->column('courseId');
            if (count($courseIds) > 0) {
                $lexiconModel->removeByWord($word);
                foreach ($courseIds as $courseId) {
                    $lexiconModel->refreshCourseCount($courseId);
                }
            }
            $info->delete();
        } catch (Exception|PDOException|ValidateException $e) {
            throw new ValidateException($e->getMessage());
        }
        return true;
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

}